<template>
  <div class="addAndEditProjectContent">
    <!-- v-bind="{ layout: 'vertical' }" -->
    <a-form ref="formRef" v-bind="{ layout: 'vertical' }" :model="formModel" :rules="rules" :disabled="disabled">
      <a-form-item has-feedback :label="t('addAndEditProject' , '项目名称')" name="name">
        <a-input v-model:value="formModel.name" autocomplete="off" :placeholder="t('common','请输入')" />
      </a-form-item>
      <div class="subTitle">{{t('addAndEditProject' , '项目设置')}}</div>
      <div style="display: flex; justify-content: space-between; flex-wrap: wrap">
        <a-form-item has-feedback :label="t('addAndEditProject' , '年级')" name="grade" style="width: 200px">
          <minDatePicker v-model:value="formModel.grade" picker="year" :disabledDate="disabledDate"
           :placeholder="t('common','请选择')"
            style="margin-right: 12px; width: 100%" />
        </a-form-item>
        <a-form-item has-feedback :label="t('addAndEditProject' , '班级')" name="gradeClass" style="width: 200px" v-if="formModel.grade">
          <a-select v-model:value="formModel.gradeClass" mode="multiple" style="width: 100%; margin-right: 12px"
            :placeholder="t('common','不限班级')">
            <a-select-option :value="item.id" v-for="item in newSelectStructure.gradeClass">{{ item.name
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item has-feedback :label="t('addAndEditProject' , '相关课程')" name="course" style="width: 200px">
          <a-select v-model:value="formModel.course" mode="multiple" style="width: 100%; margin-right: 12px"
            :placeholder="t('common','请选择')" show-search :filter-option="filterOption" :options="newSelectStructure.course"
            :field-names="{ label: 'dictName', value: 'dictValue' }">
          </a-select>
        </a-form-item>
        <a-form-item has-feedback :label="t('addAndEditProject' , '成员总数')" name="totalMemberLimit" style="width: 200px">
          <div style="display: flex; align-items: center">
            <a-input-number style="width: 100%; margin-right: 12px" v-model:value="formModel.totalMemberLimit"
              autocomplete="off" />
            {{ t('addAndEditProject' , '人') }}
          </div>
        </a-form-item>
        <div style="width: 200px"></div>
      </div>
      <a-form-item has-feedback :label="t('addAndEditProject' , '教师审核加入')" name="needAudit">
        <a-select v-model:value="formModel.needAudit" style="width: 100%; margin-right: 12px" :placeholder="t('common','请选择')">
          <a-select-option :value="1">{{ t('select' , '是') }}</a-select-option>
          <a-select-option :value="0">{{ t('select' , '否') }}</a-select-option>
          </a-select>
      </a-form-item>
      <a-form-item has-feedback :label="t('addAndEditProject' , '项目目标')" name="target">
        <!-- <a-textarea v-model:value="formModel.target" /> -->
        <minEditor v-model="formModel.target" />
      </a-form-item>

      
      <a-form-item has-feedback :label="t('addAndEditProject' , '项目描述')" name="describe">
        <!-- <a-textarea v-model:value="formModel.describe" /> -->
        <minEditor v-model="formModel.describe" />
      </a-form-item>
      <div style="display: flex; justify-content: space-between; flex-wrap: wrap">
        <a-form-item has-feedback :label="t('addAndEditProject' , '内置agent')" name="agentId" style="width: 200px">
          <a-select v-model:value="formModel.agentId" style="width: 100%; margin-right: 12px" :placeholder="t('common','请选择')"
            show-search :filter-option="filterOption" :options="newSelectStructure.learningDify"
            :field-names="{ label: 'name', value: 'id' }">
          </a-select>
        </a-form-item>
        <a-form-item has-feedback :label="t('addAndEditProject' , '推荐学习周')" name="learningCycle">
          <a-input-number id="inputNumber" v-model:value="formModel.learningCycle" :min="1" :max="999"
            style="width: 200px" />
        </a-form-item>
        <div style="width: 200px"></div>
      </div>
      <a-form-item has-feedback :label="t('addAndEditProject' , '项目周期')" name="startTime">
        <minRangePicker style="width: 100%" picker="datetime" v-model:startTime="formModel.startTime"
          v-model:endTime="formModel.endTime" />
      </a-form-item>
      <a-form-item has-feedback :label="t('addAndEditProject' , '评分标准')" name="scoreStandard">
        <!--        <a-textarea v-model:value="formModel.scoreStandard" />-->
        <minEditor v-model="formModel.scoreStandard" />
      </a-form-item>
      <a-form-item has-feedback :label="t('addAndEditProject' , '副指导老师')" name="coTeacherIds">
        <a-select v-model:value="formModel.coTeacherIds" :field-names="{ label: 'name', value: 'id' }"
          :options="newSelectStructure.coTeacherIds" :placeholder="t('common','请选择')" mode="multiple" style="width: 100%" show-search
          :filter-option="coTeacherFilterOption"></a-select>
      </a-form-item>

      <a-form-item has-feedback :label="t('addAndEditProject' , '项目图片')" name="coverImg">
        <minUploadImage :disabled="disabled" v-model="formModel.coverImg" v-model:previewImage="formModel.coverImgUrl"
          :customUploadImage="customUploadImage" />
      </a-form-item>

      <a-form-item v-if="!disabled" style="text-align: center; padding-top: 20px">
        <a-button type="primary" @click="handleSubmit" :loading="loading">{{t('common','提交')}}</a-button>
        <a-button style="margin-left: 20px" @click="handleCancel">{{t('common','取消')}}</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons-vue'

import minDatePicker from '@/components/common/minDatePicker.vue'
import minRangePicker from '@/components/common/minRangePicker.vue'
import minUploadImage from '@/components/common/minUploadImage.vue'
import minMultipleUploadImage from '@/components/common/minMultipleUploadImage.vue'
import {
  ossUpload,
  teacherGradeClassFindAll,
  typeCategory,
  teacherList,
} from '@/request/addAndEditProject'
import { learningDifyList } from '@/request/teacher/courseAI'
import { defineProps, ref, defineEmits, watch } from 'vue'
import { message } from 'ant-design-vue'
import { t } from '@/i18n'
import minEditor from '@/components/common/minEditor.vue'

const filterOption = (input, option) => {
  return option.dictName.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
const coTeacherFilterOption = (input, option) => {
  return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

const { modelValue, customUploadImage, rules, disabled, selectStructure } =
  defineProps({
    modelValue: Object,
    selectStructure: {
      type: Object,
      default: {},
    },
    customUploadImage: {
      type: Function,
      default: async (info) => {
        let res = await ossUpload({
          file: info.file,
          dir: 'teacher/avatar',
        })
        if (res) return res.data
      },
    },
    rules: {
      type: Object,
      default: {
        name: [{ required: true, message: t('common', '请输入'), trigger: 'change' }],
        // grade: [{ required: true, message: t('common', '请输入'), trigger: 'change' }],
        groupMemberLimit: [
          { required: true, message: t('common', '请输入'), trigger: 'change' },
        ],
        category: [{ required: true, message: t('common', '请选择'), trigger: 'change' }],
        template: [{ required: true, message: t('common', '请选择'), trigger: 'change' }],
        // course: [
        //   {
        //     required: true,
        //     message: t('common', '请选择'),
        //     trigger: 'change',
        //     type: 'array',
        //   },
        // ],
        totalMemberLimit: [
          { required: true, message: t('common', '请输入'), trigger: 'change' },
        ],
        devModel: [{ required: true, message: t('common', '请输入'), trigger: 'change' }],
        target: [{ required: true, message: t('common', '请输入'), trigger: 'change' }],
        needAudit: [{ required: true, message: t('common', '请选择'), trigger: 'change' }],
        difficulty: [{ required: true, message: t('common', '请输入'), trigger: 'change' }],
        describe: [{ required: true, message: t('common', '请输入'), trigger: 'change' }],
        registrationStartTime: [
          { required: true, message: t('common', '请输入'), trigger: 'change' },
        ],
        startTime: [{ required: true, message: t('common', '请输入'), trigger: 'change' }],
        coverImg: [{ required: true, message: t('common', '请选择'), trigger: 'change' }],
        agentId: [{ required: true, message: t('common', '请选择'), trigger: 'change' }],
        projectJobDTOList: [
          {
            async validator(_rule, value) {
              const isValid = value.every(
                (item) => item.name && item.requiredNum && item.skill
              )
              return isValid
                ? Promise.resolve()
                : Promise.reject(t('addAndEditProject', '请完善岗位信息'))
            },
            trigger: 'change',
          },
        ],
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  })
const formRef = ref()
const teacherStructure = ref([])
const loading = ref(false)
const formModel = ref({ ...modelValue })
const newSelectStructure = ref({
  ...selectStructure,
  template: [{ label: t('common', '经典'), value: 0 }, { label: t('common', '多组协作'), value: 1 }],
})
const emit = defineEmits(['handleSubmit', 'handleCancel'])

watch(
  () => modelValue,
  (newval) => {
    formRef?.value?.resetFields()
    formModel.value = { ...newval }
  }
)
watch(
  () => selectStructure,
  (newval) => {
    newSelectStructure.value = {
      ...newSelectStructure.value,
      ...newval,
    }
  }
)

watch(
  () => formModel.value.coverImg,
  async (newval) => {
    formRef.value.validateFields('coverImg')
  }
)

const gradeShow = async () => {
  let res = await teacherGradeClassFindAll({
    'search_AND_EQ_grade.year': formModel.value.grade,
  })
  if (!res.data) return
  formModel.value.gradeClass = formModel.value.gradeClass
    ? [...formModel.value.gradeClass]
    : []
  newSelectStructure.value.gradeClass = res.data
}
watch(
  () => formModel.value.grade,
  async (newval) => {
    gradeShow()
  }
)
const firstShow = async () => {
  let res = {
    类型: await typeCategory({ field: 'project_category' }),
    课程: await typeCategory({ field: 'course_category' }),
    开发模型: await typeCategory({ field: 'dev_model' }),
    教师列表: await teacherList(),
    课程AI: await learningDifyList(),
  }
  if (res['类型']) newSelectStructure.value.category = res['类型'].data
  if (res['课程']) newSelectStructure.value.course = res['课程'].data
  if (res['开发模型']) newSelectStructure.value.devModel = res['开发模型'].data
  if (res['教师列表'])
    newSelectStructure.value.coTeacherIds = res['教师列表'].data
  if (res['课程AI']) newSelectStructure.value.learningDify = res['课程AI'].data
  if (formModel.value.grade) gradeShow()
}
firstShow()
const disabledDate = (time) => {
  return (
    new Date(`${new Date().getFullYear() - 6}/12/31`).getTime() > time.valueOf()
  )
}

const handleSubmit = async () => {
  let v = await formRef.value.validate().catch((err) => false)
  if (!v) return message.error(t('common', '请检查表单数据'))
  emit('handleSubmit', {
    ...formModel.value,
  })
}
const handleCancel = () => {
  emit('handleCancel')
}

const handleClick = async ({ name, record, index }) => {
  switch (name) {
    case '弹窗_增加招募信息':
      formModel.value.projectJobDTOList.push({})
      break
    case '弹窗_删除招募信息':
      formModel.value.projectJobDTOList.splice(index, 1)
      break
  }
}
</script>

<style lang="scss" scoped>
.subTitle {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}

.required {
  position: relative;
  /* padding-left: 30rpx; */
}

.required::before {
  content: '*';
  font-size: 16px;
  color: red;
  position: absolute;
  top: 0;
  bottom: 0;
  left: -10px;
  margin: auto;
  display: flex;
  align-items: center;
}
</style>
